package com.caocaog.market.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.caocaog.market.entity.Member;
import com.caocaog.market.error.ApiErrorCode;
import com.caocaog.market.service.MemberService;
import com.caocaog.market.session.MemberSession;
import org.jeecg.common.exception.JeecgBootException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Objects;

/**
 * Controller父类 service统一管理
 *
 * @author admin
 * Date 2021/6/04 11:25 上午
 */
public class BaseController {

    @Autowired
    protected MemberService memberService;


    /**
     * 查询用户是否存在
     * @param memberId
     * @return
     */
    protected void verifyUser(String memberId) {
        if(memberId==null) {
            throw new JeecgBootException(ApiErrorCode.LACK_TOKEN.getMessage());
        }
        LambdaQueryWrapper<Member> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Member::getId, memberId);
        int count = memberService.count(queryWrapper);
        if (count<0) {
            throw new JeecgBootException(ApiErrorCode.LACK_TOKEN.getMessage());
        }
    }

    /**
     * 获取加验证userMessage
     * @return
     */
    protected Member verifyUserForApp() {
        MemberSession userSession = getUserForAppSession();
        if (userSession == null) {
            throw new JeecgBootException(ApiErrorCode.LACK_TOKEN);
        }
        Member member = memberService.getById(userSession.getMemberId());
        if (member == null) {
            throw new JeecgBootException(ApiErrorCode.LACK_TOKEN);
        }
        return member;
    }

    protected MemberSession getUserForAppSession() {
        HttpSession session = getRequest().getSession();
        return (MemberSession) session.getAttribute(MemberSession.USER);
    }



    private HttpServletRequest getRequest() {
        return ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
    }

}

